/**
 * 版权所有 2009-2012山东新北洋信息技术股份有限公司
 * 保留所有权利。
 */
package com.linyaonan.leetcode.easy._53_01;

/**
 * @ProjectName: leetcode
 * @Package: com.linyaonan.leetcode.easy._53_01
 * @ClassName: Search
 * @Author: linyaonan
 * @Date: 2020/4/2 16:25
 */
public class Search {
    public int search(int[] nums, int target) {
        // 异常情况
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
            int mid = start + ((end - start) >> 1);
            if (nums[mid] >= target) {
                end = mid - 1;
            } else if (nums[mid] < target) {
                start = mid + 1;
            }
        }
        // 没找到
        if (start >= nums.length || nums[start] != target) {
            return 0;
        }
        // 找到左边
        int count = 1;
        while (start <= nums.length - 1) {
            if (nums[start] != target) {
                break;
            } else {
                start++;
                count++;
            }
        }
        return --count;
    }

}
